package com.feihua.starter.service.impl;


import com.feihua.starter.comm.Constants;
import com.feihua.starter.comm.component.MsgTemplate;
import com.feihua.starter.service.api.*;
import com.feihua.starter.service.mapper.HdbActivityPoMapper;
import com.feihua.starter.service.modules.hdb.dto.*;
import com.feihua.starter.service.modules.hdb.po.*;
import com.github.pagehelper.Page;
import feihua.jdbc.api.pojo.BasePo;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.service.impl.ApiBaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * This class was generated by MyBatis Generator.
 *
 * @author revolver 2018-06-29 22:26:31
 */
@Service
public class ApiHdbActivityPoServiceImpl extends ApiBaseServiceImpl<HdbActivityPo, HdbActivityDto, String> implements ApiHdbActivityPoService {
    @Autowired
    HdbActivityPoMapper hdbActivityPoMapper;

    @Autowired
    private ApiHdbImagePoService apiHdbImagePoService;

    @Autowired
    private ApiHdbScenicSpotPoService apiHdbScenicSpotPoService;

    @Autowired
    private ApiHdbAttendPoService apiHdbAttendPoService;

    @Autowired
    private ApiHdbMsgPoService apiHdbMsgPoService;

    public ApiHdbActivityPoServiceImpl() {
        super(HdbActivityDto.class);
    }

    @Override
    public PageResultDto<HdbActivityDto> searchByMultiTable(SearchHdbActivitysConditionDto dto, PageAndOrderbyParamDto pageAndOrderbyParamDto) {
        Page p = super.pageAndOrderbyStart(pageAndOrderbyParamDto);
        List<HdbActivityDto> list = hdbActivityPoMapper.searchByMultiTable(dto);
        return new PageResultDto(list, this.wrapPage(p));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public HdbActivityDto addOrUpdateHdbActivity(HdbActivityDto hdbActivityDto, Boolean isUpdate) throws Exception {
        if (isUpdate) {
            hdbActivityDto = updateHdbActivity(hdbActivityDto);
        } else {
            hdbActivityDto = addHdbActivity(hdbActivityDto);
        }
        return hdbActivityDto;
    }

    /**
     * 添加活动
     *
     * @param dto
     *
     * @return
     */
    private HdbActivityDto addHdbActivity(HdbActivityDto dto) throws Exception {
        HdbActivityPo hdbActivityPo = new HdbActivityPo();
        BeanUtils.copyProperties(dto, hdbActivityPo);
        hdbActivityPo.setReview(Constants.ActivityReview.NONE.getCode());
        super.preInsert(hdbActivityPo, dto.getCreateBy());
        HdbActivityDto hdbActivityDto = super.insert(hdbActivityPo);
        dto.setId(hdbActivityDto.getId());
        //添加活动图片
        apiHdbImagePoService.addOrUpdate(dto.getHdbImages(), hdbActivityDto.getId(), dto.getCreateBy());
        //添加景点
        if (dto.getHdbScenicSpots() != null && dto.getHdbScenicSpots().size() > 0) {
            List<HdbScenicSpotDto> hdbScenicSpotDtos = dto.getHdbScenicSpots();
            for (HdbScenicSpotDto hdbScenicSpotDto : hdbScenicSpotDtos) {

                HdbScenicSpotPo hdbSenicSpotPo = new HdbScenicSpotPo();
                BeanUtils.copyProperties(hdbScenicSpotDto, hdbSenicSpotPo);
                hdbSenicSpotPo.setActivityId(hdbActivityDto.getId());
                apiHdbScenicSpotPoService.preInsert(hdbSenicSpotPo, dto.getCreateBy());
                HdbScenicSpotDto scenicSpotDto = apiHdbScenicSpotPoService.insert(hdbSenicSpotPo);
                hdbScenicSpotDto.setId(scenicSpotDto.getId());
                //添加景点图片
                apiHdbImagePoService.addOrUpdate(hdbScenicSpotDto.getHdbImages(), scenicSpotDto.getId(), dto.getCreateBy());
            }
        }
        //添加参与人
        HdbAttendPo hdbAttendPo = new HdbAttendPo();
        hdbAttendPo.setActivityId(hdbActivityDto.getId());
        hdbAttendPo.setUserId(hdbActivityDto.getLedUserId());
        hdbAttendPo.setStatus(BasePo.YesNo.Y.name());
        hdbAttendPo.setType(Constants.UserType.CAPTAIN.getCode());
        apiHdbAttendPoService.preInsert(hdbAttendPo, dto.getCreateBy());
        apiHdbAttendPoService.insert(hdbAttendPo);
        HdbMsgPo msgPo = new HdbMsgPo();
        msgPo.setReadFlag(BasePo.YesNo.N.name());
        msgPo.setUserId(hdbAttendPo.getUserId());
        msgPo.setActivityId(hdbAttendPo.getActivityId());
        msgPo.setSources(Constants.MsgSource.MSG_SYSTEM.getCode());
        msgPo.setTitle(Constants.MsgSource.MSG_SYSTEM.getName());
        msgPo.setContent(String.format(MsgTemplate.add_activity_msg, hdbActivityDto.getTitle()));
        apiHdbMsgPoService.preInsert(msgPo, dto.getCreateBy());
        apiHdbMsgPoService.insert(msgPo);
        return dto;
    }

    /**
     * 更新活动
     *
     * @param dto
     *
     * @return
     */
    private HdbActivityDto updateHdbActivity(HdbActivityDto dto) throws Exception {
        HdbActivityPo hdbActivityPo = new HdbActivityPo();
        BeanUtils.copyProperties(dto, hdbActivityPo);

        super.preUpdate(hdbActivityPo, dto.getUpdateBy());
        super.updateByPrimaryKey(hdbActivityPo);
        //添加活动图片
        apiHdbImagePoService.addOrUpdate(dto.getHdbImages(), hdbActivityPo.getId(), dto.getUpdateBy());
        //添加景点
        if (dto.getHdbScenicSpots() != null && dto.getHdbScenicSpots().size() > 0) {
            List<HdbScenicSpotDto> hdbScenicSpotDtos = dto.getHdbScenicSpots();
            for (HdbScenicSpotDto hdbScenicSpotDto : hdbScenicSpotDtos) {

                HdbScenicSpotPo hdbSenicSpotPo = new HdbScenicSpotPo();
                BeanUtils.copyProperties(hdbScenicSpotDto, hdbSenicSpotPo);
                hdbSenicSpotPo.setActivityId(hdbActivityPo.getId());
                if (hdbSenicSpotPo.getId() != null) {
                    apiHdbScenicSpotPoService.preUpdate(hdbSenicSpotPo, dto.getUpdateBy());
                    apiHdbScenicSpotPoService.updateByPrimaryKey(hdbSenicSpotPo);
                } else {
                    apiHdbScenicSpotPoService.preInsert(hdbSenicSpotPo, dto.getCreateBy());
                    final HdbScenicSpotDto insert = apiHdbScenicSpotPoService.insert(hdbSenicSpotPo);
                    hdbScenicSpotDto.setId(insert.getId());
                }
                //添加景点图片
                apiHdbImagePoService.addOrUpdate(hdbScenicSpotDto.getHdbImages(), hdbScenicSpotDto.getId(), dto.getUpdateBy());
            }
        }
        return dto;
    }

    @Transactional(readOnly = true)
    @Override
    public HdbActivityDto selectById(String id) {
        return hdbActivityPoMapper.selectById(id);
    }

    /**
     * @param activityId 活动ID
     * @param userId     用户ID
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public HdbActivityDto copyActivity(String activityId, String userId) throws Exception {
        HdbActivityDto dto = hdbActivityPoMapper.selectById(activityId);
        dto.setId(null);
        dto.setLedUserId(userId);
        dto.setPublish(BasePo.YesNo.N.name());
        dto.setCreateBy(userId);
        dto.setReview(Constants.ActivityReview.NONE.getCode());
        dto.setApplyTime(null);
        dto.setStartTime(null);
        dto.setEndTime(null);
        if (Constants.ActivityType.SELF.equals(dto.getType())) {
            dto.setStatus(Constants.ActivityStatus.NOT_START.getCode());
        } else {
            dto.setStatus(Constants.ActivityStatus.APPLYING.getCode());
        }
        if (CollectionUtils.isNotEmpty(dto.getHdbImages())) {
            List<HdbImageDto> hdbImages = dto.getHdbImages();
            for (HdbImageDto hdbImage : hdbImages) {
                hdbImage.setId(null);
            }
        }
        if (CollectionUtils.isNotEmpty(dto.getHdbScenicSpots())) {
            List<HdbScenicSpotDto> hdbScenicSpots = dto.getHdbScenicSpots();
            for (HdbScenicSpotDto hdbScenicSpot : hdbScenicSpots) {
                hdbScenicSpot.setId(null);
                if (CollectionUtils.isNotEmpty(hdbScenicSpot.getHdbImages())) {
                    List<HdbImageDto> hdbImages = hdbScenicSpot.getHdbImages();
                    for (HdbImageDto hdbImage : hdbImages) {
                        hdbImage.setId(null);
                    }
                }
            }
        }
        dto = addHdbActivity(dto);
        return dto;
    }

    @Transactional(readOnly = true)
    @Override
    public List<HdbActivityPo> selectTimingByNow(String type, String status, Date now, Integer dayCount) {
        return hdbActivityPoMapper.selectTimingByNow(type, status, now, dayCount);
    }

    /**
     * @param hdbReviewDto activityId  活动ID  review      审核（1，未审核，2，审核通过，3，审核失败） msg         审核信息 loginUserId 当前登录用户
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int activityReview(HdbReviewDto hdbReviewDto) {

        HdbActivityPo hdbActivityPo = hdbActivityPoMapper.selectByPrimaryKey(hdbReviewDto.getActivityId());
        hdbActivityPo.setReview(hdbReviewDto.getReview());
        hdbActivityPo.setUpdateAt(new Date());
        int i = hdbActivityPoMapper.updateByPrimaryKeySelective(hdbActivityPo);

        HdbMsgPo msgPo = new HdbMsgPo();
        msgPo.setReadFlag(BasePo.YesNo.N.name());
        msgPo.setUserId(hdbActivityPo.getCreateBy());
        msgPo.setActivityId(hdbActivityPo.getId());
        msgPo.setSources(Constants.MsgSource.MSG_REVIEW.getCode());
        msgPo.setTitle(Constants.MsgSource.MSG_REVIEW.getName());
        msgPo.setContent(String.format(MsgTemplate.review_activity_msg, hdbActivityPo.getTitle(), Constants.ActivityReview.getEnumBy(hdbReviewDto.getReview()).getName(), StringUtils.isNoneBlank(hdbReviewDto.getMsg()) ? "，信息：" + hdbReviewDto.getMsg() : ""));
        apiHdbMsgPoService.preInsert(msgPo, hdbReviewDto.getLoginUserId());
        apiHdbMsgPoService.insert(msgPo);
        //
        msgPo.setId(null);
        msgPo.setUserId(hdbReviewDto.getLoginUserId());
        msgPo.setContent(String.format(MsgTemplate.review_activity_msg_manager, hdbActivityPo.getTitle(), Constants.ActivityReview.getEnumBy(hdbReviewDto.getReview()).getName(), StringUtils.isNoneBlank(hdbReviewDto.getMsg()) ? "，信息：" + hdbReviewDto.getMsg() : ""));
        apiHdbMsgPoService.insert(msgPo);
        return i;
    }

}